import React, { useRef, FC, forwardRef, useImperativeHandle, useState, useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import MyTable from '@/components/common/table'
import Metric from '@/api/metric'
import { modalLayoutLg } from '@/config/layout'
import { Button, Input, DatePicker, Select, Modal, Cascader,Spin, Upload, Table, Form, Steps, Row, Col, Tabs, Card, Radio, message } from 'antd';
import MyDefineSelect from '@/components/common/myDefineSelect'
import $axios from '@/utils/axios';
import { fn } from 'moment'
const {Option} = Select;
const columns = [

]
const RoleList: FC = () => {
  const tableRef: RefType = useRef()
  const AddTatgetMComRef: RefType = useRef()
  
  const searchConfigList = [
    {
      key: 'measureName',
      slot: <Input placeholder="请输入指标名称" allowClear />,
      rules: [],
      initialValue: ''
    }
    
  ];

  useEffect(()=>{
    columns.push({
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      key: 'index',
      width: '80px',
      fixed: 'left',
      render: (text, record, index) => {
        return index + 1
      }
    })
    for (let i in keyObj) {
      let width = keyObj[i].length * 16
      let column = {
        title: keyObj[i],
        dataIndex: i,
  
        key: i,
        render: (txt, record) => {
          return <div style={{ minWidth: width + 'px' }}>
            {txt}
          </div>
        }
      };
      columns.push(column)
    }
    columns.push({
      title: '操作',
      align: 'left',
      dataIndex: 'scan',
      key: 'scan',
      width: '150px',
      fixed: 'right',
      render: (text, record, index) => {
        return <div>
        <Button className="btn" onClick={()=>edit(record.measureCode)} size="small">编辑</Button>
        <Button style={{marginLeft:'10px'}} className="btn" onClick={()=>del(record.measureCode)} size="small">删除</Button>
      </div>
      }
    })
  },[])
  
  // 新增按钮
  const AddBtn = () => (
    <Button className="fr" onClick={add} type="primary">
      新增指标定义
    </Button>
  )
  // 添加
  const add = () => {
    AddTatgetMComRef.current.init()
  }
   // 添加
  const edit = (id) => {
    AddTatgetMComRef.current.init(id);
  }
  // 删除
  const del = (id:any) => {
    Modal.confirm({
      title: '确认删除？',
      
      onOk() {
        // Role.roleDel({
        //   roleid:record.roleid,
        //   isFormData:true
        // }).then(()=>{
        //   tableRef.current.update();
        // })
        $axios.delete('/dm/api/metric/define/del',{
          ids:id,
          'isBody':true
        }).then((res)=>{
          tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  return (
    <>
      <div>
        {/* <BatchDel /> */}
        <AddBtn />
      </div>
      <MyTable
        apiFun={Metric.metricDefineList}
        columns={columns}
        ref={tableRef}
        searchConfigList={searchConfigList}
        extraProps={{ results: 10 }}
      />
      <AddTatgetMCom ref={AddTatgetMComRef} callback={() => {
        tableRef.current.update();
      }} />
    </>
  )
}
export default withRouter(RoleList)

const AddTatgetM = (props, refs) => {

  const [form] = Form.useForm()
  // const [fileList,setfileList] = useState([]);
  const [measureClassData, setmeasureClassData] = useState([]);
  const { setFieldsValue, resetFields } = form
  const [code, setCode] = useState('')
  const [isModalVisible, setIsModalVisible] = useState(false);

  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };
  useEffect(()=>{
    $axios.get('/dm/api/metric/define/measure-class-tree').then((res)=>{
      console.log(res);
      let data = res['data']?res['data']:[];
      data = handleMeasureClassData(data);
      setmeasureClassData(data);
    })
  },[])
  const handleMeasureClassData = (data)=>{
    data.map((e,i)=>{
      data[i]['value'] = e['measureTypeName'];
      data[i]['label'] = e['measureTypeName'];
      if(data[i]['children']&&data[i]['children'].length>0){
        data[i]['children'] = handleMeasureClassData(data[i]['children']);
      }
    })
    return data;
  }
  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      const Obj = form.getFieldsValue()
      console.log(Obj);
      Obj['measureLClass'] = Obj['measureClass'][0];
      Obj['measureMClass'] = Obj['measureClass'][1];
      Obj['measureSClass'] = Obj['measureClass'][2];
      const multipleArr = ['timeGranularity','responsibilityDept','useDept','statRule','statDim'];
      multipleArr.map((e,i)=>{
        Obj[e] = Obj[e].join('、');
      })
      console.log(Obj);
      let fn = code?$axios.put:$axios.post;
      let url = code?'/dm/api/metric/define/edit':'/dm/api/metric/define/add'
      fn(url, Obj)
        .then((res) => {
          handleCancel();
        })
        .catch((err) => {
          
        });


    }).catch(info => {

    })
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setCode('');
    resetFields();
    props.callback && props.callback();
  };
  useImperativeHandle(refs, () => ({
    init: (id) => {
      if(id){
        setCode(id);
        getDetail(id);
      }else{
        resetFields();
      }
      showModal();
      // setfileList([]);
    }
  }))
  const getDetail = (id)=>{
    $axios.get('/dm/api/metric/define/detail?measureCode='+id).then((res)=>{
      console.log(res);
      let data = res['data'];
      let multipleObj = {};
      // const multipleArr = ['timeGranularity','responsibilityDept','useDept','statRule','statDim'];
      // multipleArr.map((e,i)=>{
      //   multipleObj[e] = data[e].split('、');
      // })
      setFieldsValue({
        ...data,
        ...{
          measureClass:[
            data['measureLClass'],data['measureMClass'],data['measureSClass']
          ]
        },
        ...multipleObj
      });
    })
  }
  const getFormControlByKey = (key) => {
    switch (key) {
      case 'measureClass'://指标类
        return <Cascader disabled={code?true:false}  options={measureClassData} placeholder="选择类" />
      case 'isNegativeListMeasure'://负面指标
        return <Select>
          <Option value="是">是</Option>
          <Option value="否">否</Option>
        </Select>
      case 'measureType'://指标类别
      case 'timeGranularity'://时间粒度
      case 'responsibilityDept'://"责任部门",
      case 'useDept'://使用部门
      case 'statRule'://统计口径
      case 'statDim'://统计维度
      case 'polymerizationWay'://聚合方式
      case 'getCountWay'://取数方式
        return <MyDefineSelect
          url={keyGetDataObj[key]['url']}
          namekey={keyGetDataObj[key]['name']}
          idkey={keyGetDataObj[key]['name']}
          requestMethod="get"
          placeholder={keyObjUse[key]}
          type={"2"}
          multiple={['timeGranularity','responsibilityDept','useDept','statRule','statDim'].indexOf(key)!==-1}
          formatIdKey={(key) => { return Number(key) }}
        />
      case 'comments'://备注  textarea
        return <Input.TextArea />
      case 'measureCode':
        return <Input disabled={code?true:false}/>
      default:
        return <Input />
    }
  }
  const getFormControlRuleByKey = (key) => {
    return keyRuleObj[key]?[
      keyRuleObj[key]
    ]:[]
  }
  return <Modal
    title={code === '' ? "新增指标定义" : '编辑指标定义'}
    visible={isModalVisible}
    onOk={handleOk}
    onCancel={handleCancel}
    centered={true}
    width={700}
    maskClosable={false}
    bodyStyle={{
      maxHeight: window.innerHeight - 150,
      overflowY: 'auto'
    }}
  >
    <Form form={form} {...modalLayoutLg}>
      <Row>
        {
          Object.keys(keyObjUse).map((e, i) => {
            return (code==''&&e=='measureCode')?<></>:<Col span={12} key={i}>

              <Form.Item
                name={e}
                label={keyObjUse[e]}
                rules={getFormControlRuleByKey(e)}
              >
                {
                  getFormControlByKey(e)
                }
              </Form.Item>

            </Col>
          })
        }
      </Row>
    </Form>
  </Modal>
}
const AddTatgetMCom = forwardRef(AddTatgetM);


let keyObj = {
  "measureName": "指标名称",
  "measureAbbName": "指标简称",
  "measureCode": "指标编码",
  "measureType": "指标类型",
  "measureAlias": "指标别名",
  "measureLClass": "指标大类",
  "measureMClass": "指标中类",
  "measureSClass": "指标小类",
  "measureCategory": "指标类别",
  "measureUnit": "计量单位",
  "unitSign": "单位符号",
  "calculateFormula": "计算公式",
  "calculateFormulaCode": "计算公式编码",
  "measureDefine": "指标定义",
  "bizDataSource": "业务数据源",
  // "timeGranularity": "时间粒度",
  // "responsibilityDept": "责任部门",
  // "responsibilityJobs": "责任岗位",
  // "useDept": "使用部门",
  // "isNegativeListMeasure": "负面指标",
  // "statRule": "统计口径",
  // "statDim": "统计维度",
  // "polymerizationWay": "聚合方式",
  // "getCountWay": "取数方式",
  "comments": "备注",
};
let keyObjUse = {
  "measureName": "指标名称",
  "measureAbbName": "指标简称",
  "measureCode": "指标编码",
  "measureType": "指标类型",
  "measureAlias": "指标别名",
  "measureClass": "指标类",
  "measureCategory": "指标类别",
  "measureUnit": "计量单位",
  "unitSign": "单位符号",
  "calculateFormula": "计算公式",
  "calculateFormulaCode": "计算公式编码",
  "measureDefine": "指标定义",
  "bizDataSource": "业务数据源",
  // "timeGranularity": "时间粒度",
  // "responsibilityDept": "责任部门",
  // "responsibilityJobs": "责任岗位",
  // "useDept": "使用部门",
  // "isNegativeListMeasure": "负面指标",
  // "statRule": "统计口径",
  // "statDim": "统计维度",
  // "polymerizationWay": "聚合方式",
  // "getCountWay": "取数方式",
  "comments": "备注",
};
let keyRuleObj = {
  "measureName": {
    required: true,
    message: '请输入指标名称'
  },
  "measureAbbName": {
    required: true,
    message: '请输入指标简称'
  },
  "measureCode":{
    required: true,
    message: '请选择指标编码'
  },
  "measureType": {
    required: true,
    message: '请选择指标类型'
  },
  "measureClass": {
    required: true,
    message: '请选择指标类'
  },
  "measureUnit":{
    required: true,
    message: '请输入计量单位'
  },
  "unitSign": {
    required: true,
    message: '请输入单位符号'
  },
  "measureDefine": {
    required: true,
    message: '请输入指标定义'
  },
  "bizDataSource":{
    required: true,
    message: '请输入业务数据源'
  },

  // "timeGranularity": {
  //   required: true,
  //   message: '请选择时间粒度'
  // },
  // "responsibilityDept": {
  //   required: true,
  //   message: '请选择责任部门'
  // },
  // "useDept": {
  //   required: true,
  //   message: '请选择使用部门'
  // },
  // "statRule":  {
  //   required: true,
  //   message: '请选择统计口径'
  // },
  // "statDim":  {
  //   required: true,
  //   message: '请选择统计维度'
  // },
  // "getCountWay": {
  //   required: true,
  //   message: '请选择取数方式'
  // },
};
let keyGetDataObj = {
  'measureType':{//指标类别
    url:"/dm/api/metric/define/measure-type",
    name:'measureTypeName',
    method:'get'
  },
  // 'timeGranularity':{//时间粒度
  //   url:"/api/metric/define/time-granularity",
  //   name:'measureTypeName',
  //   method:'get'
  // },
  // 'responsibilityDept':{//责任部门
  //   url:"/api/metric/define/dept",
  //   name:'measureTypeName',
  //   method:'get'
  // },
  // 'useDept':{//使用部门
  //   url:"/api/metric/define/dept",
  //   name:'measureTypeName',
  //   method:'get'
  // },
  // 'statRule':{//统计口径
  //   url:"/api/metric/define/stat-rule",
  //   name:'measureTypeName',
  //   method:'get'
  // },
  // 'statDim':{//统计维度
  //   url:"/api/metric/define/stat-dim",
  //   name:'measureTypeName',
  //   method:'get'
  // },
  // 'polymerizationWay':{//聚合方式
  //   url:"/api/metric/define/get-ply-way",
  //   name:'measureTypeName',
  //   method:'get'
  // },
  // 'getCountWay':{//取数方式
  //   url:"/api/metric/define/get-count-way",
  //   name:'measureTypeName',
  //   method:'get'
  // }
}
